package top.jacktgq.lock.reentrantLock;

import top.jacktgq.utils.LogUtils;

/**
 * 
 * @Title: TestReentrantLock.java 
 * @Package top.jacktgq.lock 
 * @Description: 多线程交替输出：线程1输出 a 5次，线程2输出 b 5次，线程3输出 c 5次
 * @author CandyWall   
 * @date 2020年11月1日 下午5:49:07 
 * @version V1.0
 */
public class Demo6_1_multiThreadRunInTurn {
	private static int flag = 1; //flag为1，表示轮到t1线程打印，flag为2表示轮到t2线程打印，flag等于3表示轮到t3线程打印
	public static void main(String[] args) {
		Object lock = new Object();
		Thread t1 = new Thread(() -> {
			synchronized (lock) {
				int count = 0;	//记录打印的次数
				while(true) {
					//如果flag等于1，表示轮到t1线程打印
					if(flag == 1) {
						count++;
						flag++;
						LogUtils.log("Demo6_1_multiThreadRunInTurn", "a");
						lock.notifyAll();
					} else {
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					//如果打印了5次，就退出循环
					if(count == 5) {
						break;
					}
				}
			}
		});
		Thread t2 = new Thread(() -> {
			synchronized (lock) {
				int count = 0;	//记录打印的次数
				while(true) {
					//如果flag等于3，表示轮到t2线程打印
					if(flag == 2) {
						count++;
						flag++;
						LogUtils.log("Demo6_1_multiThreadRunInTurn", "b");
						lock.notifyAll();
					} else {
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					//如果打印了5次，就退出循环
					if(count == 5) {
						break;
					}
				}
			}
		});
		Thread t3 = new Thread(() -> {
			synchronized (lock) {
				int count = 0;	//记录打印的次数
				while(true) {
					//如果flag等于3，表示轮到t2线程打印
					if(flag == 3) {
						count++;
						flag = 1;
						LogUtils.log("Demo6_1_multiThreadRunInTurn", "c");
						lock.notifyAll();
					} else {
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					//如果打印了5次，就退出循环
					if(count == 5) {
						break;
					}
				}
			}
		});
		
		t1.start();
		t2.start();
		t3.start();
		
	}	
}
